package org.graduates.webapp.actions;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.projects.graduates.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;

@Action(results = { @Result(name = "input", type = "json"), @Result(name = "success", type = "json") })
public class SubmitLoginAction extends BaseAction {

	private Logger logger = LoggerFactory.getLogger(SubmitLoginAction.class);
	private static final long serialVersionUID = -3003717233307163863L;

	private User user;

	private long pid = 0L;

	private boolean success = false;

	public String execute() {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
		try {
			subject.login(token);
		} catch (UnknownAccountException uae) {
			logger.warn(String.format("who %s , where %s , warn : %s", token.getUsername(), token.getHost(), uae));
			return ActionSupport.INPUT;
		} catch (IncorrectCredentialsException ice) {
			logger.warn(String.format("who %s , where %s , warn : %s", token.getUsername(), token.getHost(), ice));
			return ActionSupport.INPUT;

		} catch (LockedAccountException lae) {
			logger.warn(String.format("who %s , where %s , warn : %s", token.getUsername(), token.getHost(), lae));

			return ActionSupport.INPUT;
		} catch (ExcessiveAttemptsException eae) {
			logger.warn(String.format("who %s , where %s , warn : %s", token.getUsername(), token.getHost(), eae));
			return ActionSupport.INPUT;
		} catch (Exception ee) {
			logger.warn(String.format("who %s , where %s , warn : %s", token.getUsername(), token.getHost(), ee));
			return ActionSupport.INPUT;
		}

		SecurityUtils.getSubject().getSession().setAttribute("currentUser", User.findby(token.getUsername()));
		success = true;
		pid = getCurrentPerson().getId();
		logger.warn(String.format("who %s , where %s login success", token.getUsername(), token.getHost()));
		return ActionSupport.SUCCESS;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public long getPid() {
		return pid;
	}

}
